<template>
  <div>
    <div v-if="loading" style="text-align:center; height: 100%; height:300px;padding: 0px !important;margin: 0 !important;">
      <i class="el-icon-loading"></i> 词云加载中...
    </div>
    <div v-else
         id="wordcloud"
         ref="wordcloud"
         style="width: 100%; height: 300px;padding: 0px !important;margin: 0px !important;">
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import 'echarts-wordcloud';
import { ReadByLevel } from "@/api/job";

export default {
  name: 'PlotWordCloud',

  props: {
    level: {
      type: String,
      required: true
    }
  },

  data() {
    return {
      loading: true,
      words: [],
      chart: null,
      colorRange: [
        '#e0f3db', // 低频
        '#a8ddb5',
        '#4eb3d3', // 中频
        '#2b8cbe',
        '#0868ac', // 高频
        '#d73027'  // 最高频
      ]
    };
  },

  async mounted() {
    try {
      const res = await this.fetchDataByLevel(this.level);
      this.words = res.data.data || [];
      this.normalizeWordFrequencies();
      this.loading = false;
      await this.$nextTick();
      this.initChart();
    } catch (error) {
      console.error('读取词云数据失败:', error);
      this.loading = false;
    }
  },

  methods: {
    async fetchDataByLevel(level) {
      switch (level) {
        case 'elementary': return await ReadByLevel('elementary');
        case 'intermediate': return await ReadByLevel('intermediate');
        case 'upper_intermediate': return await ReadByLevel('upper_intermediate');
        case 'advanced': return await ReadByLevel('advanced');
        default: throw new Error(`未知 level：${level}`);
      }
    },

    normalizeWordFrequencies() {
      if (this.words.length === 0) return;

      const counts = this.words.map(item => item.count);
      const max = Math.max(...counts);
      const min = Math.min(...counts);

      this.words.forEach(item => {
        const ratio = (item.count - min) / (max - min);
        item.normalizedValue = ratio;

        if (ratio > 0.85) {
          item.color = this.colorRange[5];
        } else if (ratio > 0.6) {
          item.color = this.colorRange[4];
        } else if (ratio > 0.4) {
          item.color = this.colorRange[3];
        } else if (ratio > 0.2) {
          item.color = this.colorRange[2];
        } else if (ratio > 0.05) {
          item.color = this.colorRange[1];
        } else {
          item.color = this.colorRange[0];
        }
      });
    },

    initChart() {
      this.chart = echarts.init(this.$refs.wordcloud);

      const option = {
        tooltip: {
          show: true,
          formatter: params => {
            const word = this.words.find(w => w.word === params.name);
            return `
              <div style="font-size:14px;color:#333;font-weight:bold">
                ${params.name}<br/>
                频率: ${word?.count || 0}<br/>
                中文: ${word?.chinese || '暂无翻译'}
              </div>
            `;
          }
        },
        series: [{
          type: 'wordCloud',
          shape: 'pentagon',
          sizeRange: [12, 80],
          rotationRange: [-45, 45],
          gridSize: 8,
          drawOutOfBound: false,
          textStyle: {
            fontFamily: 'Microsoft YaHei, sans-serif',
            fontWeight: 'bold',
          },
          emphasis: {
            focus: 'self',
            textStyle: {
              fontSize: 36,
              shadowBlur: 12,
              shadowColor: '#999',
              transition: 'all 0.3s ease'
            }
          },
          data: this.words.map(item => ({
            name: item.word,
            value: item.count,
            textStyle: {
              color: item.color
            }
          }))
        }]
      };

      this.chart.setOption(option);
      window.addEventListener('resize', this.handleResize);
    },

    handleResize() {
      this.chart?.resize();
    }
  },

  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      window.removeEventListener('resize', this.handleResize);
    }
  }
};
</script>

<style>
#wordcloud {
  border-radius: 8px;
  max-width: 900px;
}
</style>
